package com.hanqian.zebra.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.hanqian.zebra.other.AjaxResult;
import com.hanqian.zebra.util.ZebraUtil;
import org.apache.tomcat.util.buf.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;

/**
 * zebra打印
 * ============================================================================
 * author : dzw
 * createDate:  2020/6/24 。
 * ============================================================================
 */
@RestController
public class PrintController {

	@PostMapping("print")
	public AjaxResult print(String printURL, String type, String codes){

		if(StrUtil.isBlank(printURL)){
			return AjaxResult.error("打印机地址为空");
		}

		if(StrUtil.isBlank(codes)){
			return AjaxResult.error("编码为空");
		}

		if(!StrUtil.equals("1", type) && !StrUtil.equals("2", type)){
			return AjaxResult.error("未知打印类型：type=" + type);
		}

		AjaxResult ajaxResult = AjaxResult.error("打印失败");
		try {
			System.out.println("====== 接收到的参数 =======");
			System.out.println(codes);
			System.out.println("====== 接收到的参数 =======");
			codes = URLDecoder.decode(codes, "UTF-8");
			System.out.println("====== 解码后的参数 =======");
			System.out.println(codes);
			System.out.println("====== 解码后的参数 =======");
			JSONArray objects = JSON.parseArray(codes);
			for(int i = 0; i < objects.size(); i++){
				ajaxResult = ZebraUtil.print(printURL, objects.getJSONObject(i).getString("code"), Convert.toInt(type), objects.getJSONObject(i).getString("url"),objects.getJSONObject(i).getString("name"));
			}
		}catch (Exception e){
			e.printStackTrace();
			AjaxResult.error(e.getLocalizedMessage());
		}

		return ajaxResult;
	}

	@RequestMapping("test")
	public AjaxResult test(String param){
		return AjaxResult.success(param);
	}

	@RequestMapping("testPrint")
	public AjaxResult testPrint() throws Exception {
		ZebraUtil.getPrintSteamOfSmall("testtesttest", "http:www.baidu.com/s?wd=ddddddddsfsfsefsefsefsfgsgdsgsgsrg", "心肺复苏抢救车（汉科室后经）");
		return AjaxResult.success();
	}

}
